package znck.spring.serviceImp.util;


import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;

import net.sf.json.JSONObject;
import znck.spring.service.util.SMSService;
import znck.spring.service.util.SystemService;

@Service
public class SMSServiceImp implements SMSService {

	@Autowired
	SystemService systemService;
	
	
	@Override
	public String Verification_code_send(String phone, HttpSession httpsession) {
		// TODO Auto-generated method stub
		String url = systemService.getProperty_key("requestUrl");
		String appkey = systemService.getProperty_key("AppKey");
		String secret = systemService.getProperty_key("AppSecret");
		//短信签名
		String sms_free_sign_name = systemService.getProperty_key("sms_free_sign_name");
		//短信模板
		String sms_template_code = systemService.getProperty_key("sms_template_code");
		
		TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
		req.setExtend("-1");   //非已登录用户使用
		req.setSmsType("normal");
		req.setSmsFreeSignName(sms_free_sign_name);
		req.setRecNum(phone);
		req.setSmsTemplateCode(sms_template_code);
		JSONObject jsonObj = new JSONObject();
		int VerificationCode = (int)(Math.random()*90000)+10000;      //产生验证码，保证是四位数验证码
		jsonObj.accumulate("code", String.valueOf(VerificationCode));
		req.setSmsParamString(jsonObj.toString());
		AlibabaAliqinFcSmsNumSendResponse rsp;
		try {
			rsp = client.execute(req);
			JSONObject JsonRsp = JSONObject.fromObject(rsp.getBody());
			
			if(!JsonRsp.getJSONObject("error_response").isNullObject()) {   //*
				//System.out.println(JsonRsp.getJSONObject("error_response"));
				return null;
			}else {
if(JsonRsp.getJSONObject("alibaba_aliqin_fc_sms_num_send_response").getJSONObject("result").getBoolean("success") == true){
	        	
	        	httpsession.setAttribute(phone, VerificationCode);
	        	Timer timer = new Timer();
	        	timer.schedule(new TimerTask(){public void run(){
	        		httpsession.removeAttribute(phone);
	        	}}, 1000*60);//60秒后失效
	        }else{
	        	return null;
	        }
			}
		} catch (ApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		
		return String.valueOf(VerificationCode);
	}


	@Override
	public boolean SMS_Send(String phone, HttpSession httpsession) {
		// TODO Auto-generated method stub
		//System.out.println("phone:  "+phone);
		try {
			if(sendSms(phone, httpsession) != null) {
				return true;
			}else {
				return false;
			}
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	public SendSmsResponse sendSms(String phone,  HttpSession httpsession) throws ClientException {
	    //产品名称:云通信短信API产品,开发者无需替换
	    final String product = "Dysmsapi";
	    //产品域名,开发者无需替换
	    final String domain = "dysmsapi.aliyuncs.com";

	    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找)
	    final String accessKeyId = systemService.getProperty_key("msgAppID");
	    final String accessKeySecret = systemService.getProperty_key("msgAppSecret");

        //可自助调整超时时间,相当于设置了一个静态变量
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(systemService.getProperty_key("sms_free_sign_name"));
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(systemService.getProperty_key("sms_template_code"));
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        //request.setTemplateParam("{\"name\":\"Tom\", \"code\":\"123\"}");
        JSONObject jsonObj = new JSONObject();
		int VerificationCode = (int)(Math.random()*90000)+10000;      //产生验证码，保证是四位数验证码
		jsonObj.accumulate("code", String.valueOf(VerificationCode));
		request.setTemplateParam(jsonObj.toString());
        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
       //request.setOutId("yourOutId");

        //hint 此处可能会抛出异常，注意catch
      
        	SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
            	//请求成功
            	httpsession.setAttribute(phone, VerificationCode);
	        	Timer timer = new Timer();
	        	timer.schedule(new TimerTask(){public void run(){
	        		httpsession.removeAttribute(phone);
	        	}}, 1000*60);//60秒后失效
            	}
            return sendSmsResponse;
        
    }
}
